//
//  ConsulationV2AnswerViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/2.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "ConsulationV2AnswerInfoViewModel.h"

#import "ConsulationNewReplyCellModel.h"
#import "ConsulationAnswerCellModel.h"
#import "ConsulationAnsedListCell.h"

#import "ConsulationListData.h"
#import "ReplyInfoData.h"
#import "ReplysListData.h"

@interface ConsulationV2AnswerInfoViewModel()

@property (nonatomic, copy) NSString* consultID;
@property (nonatomic, assign) BOOL isCanReply;
@property (nonatomic, assign) BOOL isCanApdot;

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* reqDetailCmd;
@property (nonatomic, readwrite, strong) RACCommand* reqAdoptCmd;
@property (nonatomic, readwrite, strong) RACCommand* reqReplyCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@end

@implementation ConsulationV2AnswerInfoViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.isCanReply = NO;
    
    self.lastPage = 999;
    self.shouldMultiSections = YES;
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.freeConsulationCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
           
        @weakify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        if ([um isLogined])
        {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return nil;
            }];
        }
        else
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请登录后再操作"}]];
        }
    }];
    
    self.reqDetailCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        return [[self _requestConsulationDetail] doNext:^(id x)
        {
            @strongify(self);
            
            [self.requestRemoteDataCommand execute:@0];
        }];
    }];
    
    self.reqAdoptCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        if (!self.isCanApdot)
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                return nil;
            }];
        
        @weakify(self);
        return [self _requestAdoptSignal:input];
    }];
    
    self.reqReplyCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        return [self _requestReplySignal:input];
    }];
}

- (void)setConsultListData:(id)consultListData
{
    _consultListData = consultListData;
    
    ConsulationListData* cListData = nil;
    if ([self.consultListData isKindOfClass:[ConsulationNewReplyCellModel class]])
    {
        ConsulationNewReplyCellModel* cellModel = self.consultListData;
        cListData = cellModel.data;
    }
    else
    {
        ConsulationAnsedListCellModel* cellModel = self.consultListData;
        cListData = cellModel.data;
    }
    
    self.consultID = cListData.consultID;
}

- (RACSignal *)_requestConsulationDetail
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* strUserID = [um isLogined] ? um.userData.userID : @"";
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
    {
        @strongify(self);
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_consult_detail params:interface_param_consult_detail(self.consultID, strUserID)] subscribeNext:^(id x)
        {
            @strongify(self);
            
            ReplyInfoData* replyInfoData = [ReplyInfoData modelWithJSON:x];
            
            self.isCanApdot = replyInfoData.isUser;
            
            if (!replyInfoData.isUser && ([um.userData.identify isEqualToString:@"2"] || [um.userData.identify isEqualToString:@"4"]))
            {
                self.isCanReply = YES;
            }
            else
            {
                self.isCanReply = NO;
            }
                
            self.consulationAskCM = [[ConsulationAskCellModel alloc] initWithData:replyInfoData cellHeight:100.0f];
            
            [subscriber sendNext:replyInfoData];
            [subscriber sendCompleted];
        } error:^(NSError *error)
        {
            //错误处理
            
            [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
            [subscriber sendCompleted];
        }];
    }];
}

- (RACSignal*)_requestAdoptSignal:(NSString*)replyID
{
    @weakify(self);
    
    NSString* consultID = self.consultID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_consult_setanswer params:interface_param_consult_setanswer(consultID, replyID)] subscribeNext:^(id x)
        {
            @strongify(self)
            
            // Reload Data
            ReplyInfoData* replyInfoData = self.consulationAskCM.data;
            replyInfoData.status = @"2";
            
            for (ConsulationAnswerCellModel* curCellModel in self.dataSource[1])
            {
                ReplyListData* replyListData = curCellModel.data;
                
                if ([replyListData.replyID isEqualToString:replyID])
                {
                    replyListData.is_answer = @"1";
                }
                
                replyListData.askStatus = @"2";
                
                [curCellModel rebind:replyListData];
            }
            
            [subscriber sendNext:@"成功采纳"];
            [subscriber sendCompleted];
            
        } error:^(NSError *error)
        {
            //错误处理
            
            [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}

- (RACSignal*)_requestReplySignal:(NSString*)content
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* consultID = self.consultID;
    NSString* expertID = @"";
    if ([um.userData.identify isEqualToString:@"2"])
    {
        expertID = um.expertData.expertInfo.expertID;
    }
    else if ([um.userData.identify isEqualToString:@"4"])
    {
        expertID = um.institutionData.institutionInfo.institutionID;
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_consult_reply params:interface_param_consult_reply(consultID, expertID, content)] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    [subscriber sendNext:x[SUCommandSysMessageKey]];
                    [subscriber sendCompleted];
                    
                } error:^(NSError *error)
                {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }];
        
        return nil;
    }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    ReplyInfoData* replyInfoData = self.consulationAskCM.data;
    NSString* askStatus = replyInfoData.status;
    
    NSString* consultID = self.consultID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_consult_replylist params:interface_param_consult_replylist(consultID, @(page+1), @(List_PageSize))] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    ReplysListData* replysListData = [ReplysListData modelWithJSON:x];
                    
                    NSArray *viewModels = [replysListData.datas.rac_sequence map:^ConsulationAnswerCellModel *(ReplyListData* data)
                                           {
                                               @strongify(self)
                                               
                                               data.askStatus = askStatus;
                                               data.isAskUser = self.isCanApdot;
                                               
                                               @weakify(self);
                                               ConsulationAnswerCellModel *itemViewModel = [[ConsulationAnswerCellModel alloc] initWithData:data cellHeight:144.0f];
                                               [itemViewModel.adoptCommand.executionSignals.switchToLatest subscribeNext:^(id x)
                                               {
                                                   @strongify(self)
                                                   
                                                   if (!itemViewModel.isAdopt)
                                                   {
                                                       [self.reqAdoptCmd execute:data.replyID];
                                                   }
                                               }];
                                               
                                               return itemViewModel;
                                           }].array;
                    
                    viewModels = viewModels ? viewModels : @[];
                    
                    if (viewModels.count < List_PageSize)
                    {
                        self.lastPage = self.page;
                    }
                    
                    if (self.shouldPullUpToLoadMore)
                    {
                        if (0 == page)
                        {
                            self.dataSource = @[@[self.consulationAskCM], viewModels];
                        }
                        else
                        {
                            if (self.dataSource == nil)
                            {
                                self.dataSource = @[@[self.consulationAskCM], viewModels];
                            }
                            else
                            {
                                self.dataSource = @[@[self.consulationAskCM], [self.dataSource[1] arrayByAddingObjectsFromArray:viewModels]];
                            }
                        }
                    }
                    else
                    {
                        self.dataSource = @[@[self.consulationAskCM], viewModels];
                    }
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

@end
